import MarkdownIt from 'markdown-it'
import markdownItEmoji from 'markdown-it-emoji/dist/markdown-it-emoji.js'
import markdownItFootnote from 'markdown-it-footnote'
import markdownItContainer from 'markdown-it-container'
import markdownItKatex from 'markdown-it-katex'
import markdownItTaskLists from 'markdown-it-task-lists'
import hljs from 'highlight.js'

// 导入自定义插件
import markdownItDataset from '../plugins/markdownItDataset'
import markdownItEcharts from '../plugins/markdownItEcharts'
import markdownItContainerPlugin from '../plugins/markdownItContainer'
import markdownItMermaid from '../plugins/markdownItMermaid'
import markdownItEditable from '../plugins/markdownItEditable'


export function createMarkdownItInstance(editable = true) {
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    // 减少空段落生成
    breaks: false,
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(str, { language: lang }).value
        } catch (__) {}
      }
      return ''
    }
  })
  
  // 添加基础插件
  md
    .use(markdownItFootnote)
    .use(markdownItEmoji)
    .use(markdownItKatex)
    .use(markdownItTaskLists)
    .use(markdownItMermaid)

  // 使用自定义插件
  md.use(markdownItDataset)
  md.use(markdownItEcharts)
  md.use(markdownItContainerPlugin)

  // 只有当editable为true时才引入编辑插件
  if (editable) {
    md.use(markdownItEditable)
  }

  // 移除脚注分隔线
  md.renderer.rules.footnote_block_open = () => '<section class="footnotes">\n<ol class="footnotes-list">\n'
  md.renderer.rules.footnote_block_close = () => '</ol>\n</section>\n'

  return md
}